<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-10-18
 * Time: 下午2:42
 * 验证码
 */

namespace DB;

class VerifyCode extends RedisDefault {

  private $verifyCode;

  public function getVerifyCode(){
    return $this->verifyCode;
  }
  /**
   * 初始化生成验证码
   * @param string $email 邮箱
   */
  public function initVerifyCode(string $email){
    $verifyCode = mt_rand(100000,999999);
    $this->initSetVerifyCode($email,$verifyCode,60);
  }

  /**
   * 设置验证码
   * @param string $email 邮箱
   * @param int $code 验证码
   * @param int $timeout 有效时间
   */
  private function initSetVerifyCode(string $email, int $verifyCode, int $timeout = 60){
    $redis = self::getInstance();
    if($redis->get($email) != false){
      $redis->delete($email);
    }
    $redis->setex($email,$timeout,$verifyCode);
    $this->verifyCode = $verifyCode;
  }

  /**验证验证码是否符合
   * @param string $email
   * @param int $verifyCode
   * @return bool
   */
  public function validate(string $email, int $verifyCode):bool {
    $redis = self::getInstance();
    if ($redis->get($email) == $verifyCode){
      return true;
    }
    return false;
  }

}